package com.kfm.servlet;

import com.kfm.model.Result;
import com.kfm.model.SEmp;
import com.kfm.service.SEmpService;
import com.kfm.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// /emp?type=delete&id=1 get
// /emp?type=edit&id=1 get

// /emp?type=edit post name/email
@WebServlet("/emp")
public class EmpServlet extends HttpServlet {

    private SEmpService service = new SEmpService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");
        // 如果 type == null
        type = type == null ? "all" : type;
        switch (type) {
            case "edit" -> {
                System.out.println("修改");
            }
            case "delete" -> {
                delete(req, resp);
            }
            case "all" -> {
                all(req, resp);
            }
        }
    }

    private void all(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<SEmp> all = service.findAll();
        req.setAttribute("all", all);
        req.getRequestDispatcher("/WEB-INF/all.jsp").forward(req, resp);
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String id = req.getParameter("id");
        SEmp emp = service.findById(id);
        int rows = service.deleteById(id);
        Result result = rows > 0 ? Result.success("删除成功", 1, emp) : Result.failure("删除失败");
        req.getSession().setAttribute(Constant.MESSAGE_KEY, result);
        resp.sendRedirect("/emp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
